package com.shuai.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.Page;
import com.shuai.common.constant.AuthenticationConstant;
import com.shuai.common.constant.ChatType;
import com.shuai.common.constant.ErrorCode;
import com.shuai.common.exception.BusinessException;
import com.shuai.common.rps.BaseResponse;
import com.shuai.common.utils.MyJWTUtil;
import com.shuai.common.utils.ResultUtils;
import com.shuai.user.domain.entity.UserSession;
import com.shuai.user.domain.request.UserSessionAddRequest;
import com.shuai.user.domain.vo.MessageVO;
import com.shuai.user.domain.vo.UserSessionVO;
import com.shuai.user.service.SessionChatRecordService;
import com.shuai.user.service.UserSessionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@Validated
@RequestMapping("/session")
public class SessionController {
    @Autowired
    private UserSessionService userSessionService;

    @Autowired
    private SessionChatRecordService sessionChatRecordService;

    @GetMapping("/getUserSession")
    public BaseResponse<List<UserSessionVO>> getUserSession(@RequestHeader(AuthenticationConstant.AUTHENTICATION_HEADER) String auth) {
        String userId = (String) MyJWTUtil.getPayLoadItem(auth, AuthenticationConstant.PAYLOAD_USERID);
        if (StringUtils.isBlank(userId)) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "用户身份信息异常");
        }
        List<UserSession> userSessions = userSessionService.listUserSession(userId, ChatType.ORDINARY_CHAT);
        return ResultUtils.success(userSessions.stream().map(item -> {
            UserSessionVO userSessionVO = new UserSessionVO();
            BeanUtils.copyProperties(item, userSessionVO);
            return userSessionVO;
        }).collect(Collectors.toList()));
    }

    @GetMapping("/getUserSessionChatRecord")
    public BaseResponse<List<MessageVO>> getUserSessionChatRecord(@RequestHeader(AuthenticationConstant.AUTHENTICATION_HEADER) String auth,
                                                                  Long sessionId) {
        String userId = (String) MyJWTUtil.getPayLoadItem(auth, AuthenticationConstant.PAYLOAD_USERID);
        if (StringUtils.isBlank(userId)) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "用户身份信息异常");
        }
        List<MessageVO> messageVOS = sessionChatRecordService.listUserSessionChatRecord(userId, sessionId, ChatType.ORDINARY_CHAT);
        return ResultUtils.success(messageVOS);
    }


    @PostMapping("/addUserSession")
    public BaseResponse<Boolean> addUserSession(@RequestHeader(AuthenticationConstant.AUTHENTICATION_HEADER) String auth,
                                                @RequestBody @Valid UserSessionAddRequest userSessionAddRequest) {
        String userId = (String) MyJWTUtil.getPayLoadItem(auth, AuthenticationConstant.PAYLOAD_USERID);
        if (StringUtils.isBlank(userId)) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "用户身份信息异常");
        }
        UserSession userSession = new UserSession();
        userSession.setSessionName(userSessionAddRequest.getSessionName());
        userSession.setUserId(userId);
        userSession.setType(ChatType.ORDINARY_CHAT.getCode());
        userSessionService.save(userSession);
        return ResultUtils.success(Boolean.TRUE);
    }

    @GetMapping("/deleteUserSession")
    public BaseResponse<Boolean> deleteUserSession(@RequestHeader(AuthenticationConstant.AUTHENTICATION_HEADER) String auth,
                                                   Long sessionId) {
        String userId = (String) MyJWTUtil.getPayLoadItem(auth, AuthenticationConstant.PAYLOAD_USERID);
        if (StringUtils.isBlank(userId)) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "用户身份信息异常");
        }
        LambdaQueryWrapper<UserSession> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserSession::getSessionId, sessionId);
        queryWrapper.eq(UserSession::getUserId, userId);
        if (!userSessionService.remove(queryWrapper)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "删除会话失败，无权限");
        }
        return ResultUtils.success(Boolean.TRUE);
    }
}
